package com.hqyj.shiro;

import com.hqyj.dao.UserMapper;
import com.hqyj.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现 shiro的认证（登录—) 和授权 (权限管理)
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserMapper userMapper;
    /**
     * 授权 (权限管理)
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取认证通过的用户名
        Object userName =principals.fromRealm(this.getName()).iterator().next();
        //查询用户的角色参数
        List<String> listRole=userMapper.selectRole(userName+"");
        for(String s:listRole){
            System.err.println("角色="+s);
        }

        //创建授权对象
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        //添加角色
        simpleAuthorInfo.addRoles(listRole);
//        //添加权限
//        simpleAuthorInfo.addStringPermissions(listPower);
        return simpleAuthorInfo;
    }

    /**
     * 认证（登录)
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取登录用户的凭证
        UsernamePasswordToken t=(UsernamePasswordToken)token;
        //获取用户名
        String sysName = (String)t.getPrincipal();
        //查询用户名
        User a =userMapper.login(sysName);
        //判断用户是否存在
        if(a==null){
            throw new UnknownAccountException();
        }

        //密码校验
        AuthenticationInfo  info = new SimpleAuthenticationInfo(a.getUserName(),a.getUserPwd(),new Md5Hash(sysName), this.getName());
        return info;
    }
}
